package com.zhugang.week01;

/**
 * @program algorithms
 * @description: reverseWords
 * @author: chanzhugang
 * @create: 2022/03/20 20:30
 */
public class ReverseWords {

    public static void main(String[] args) {
        ReverseWords reverseWords = new ReverseWords();
        String str = " chan  zhu  gang!  ";
        String result = reverseWords.reverseWord(str);
        System.out.println(result);
    }

    /**
     * 翻转单词，" hello  world！ "  ->  "world! hello"
     */
    public String reverseWord(String str) {
        char[] s = str.toCharArray();
        int n = trim(s);
        if (n == 0) {
            return "";
        }
        reverse(s, 0, n - 1);
        int p = 0;
        while (p < n) {
            int r = p;
            while (r < n && s[r] != ' ') {
                r++;
            }
            reverse(s, p, r - 1);
            p = r + 1;
        }
        // 新的字符串数组
        char[] newChar = new char[n];
        for (int i = 0; i < n; i++) {
            newChar[i] = s[i];
        }
        return new String(newChar);
    }

    private int trim(char[] s) {
        // 去除前置、后置、中间多余空格
        int n = s.length;
        int i = 0;
        while (i < n && s[i] == ' ') {
            i++;
        }
        int j = n - 1;
        while (j >= 0 && s[j] == ' ') {
            j--;
        }
        int k = 0;
        while (i <= j) {
            if (s[i] == ' ') {
                if (i + 1 <= j && s[i + 1] != ' ') {
                    s[k++] = ' ';
                }
            } else {
                s[k++] = s[i];
            }
            i++;
        }
        return k;
    }

    private void reverse(char[] s, int p, int r) {
        while (p < r) {
            char temp = s[p];
            s[p] = s[r];
            s[r] = temp;
            p++;
            r--;
        }
    }

}